package com.dlc.felear.xiaoensale.adapter;

import android.content.Context;
import android.graphics.Paint;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.dlc.felear.xiaoensale.R;
import com.dlc.felear.xiaoensale.customView.ConfirmDialog;
import com.dlc.felear.xiaoensale.dao.CookingMenuDao;
import com.dlc.felear.xiaoensale.dao.MenuFoodMaterialDao;
import com.dlc.felear.xiaoensale.dao.OperatorDao;
import com.dlc.felear.xiaoensale.entity.CookingMenu;
import com.dlc.felear.xiaoensale.helper.CookingMenuMangerHelper;
import com.dlc.felear.xiaoensale.helper.SendData;

import java.util.ArrayList;
import java.util.List;


public class EmnuControltemAdapter extends BaseAdapter implements ConfirmDialog.ConfirmDialogCallback {

    private static final String TAG = "EmnuControltemAdapter";
    // 上下文
    private Context context;
    // 数据
    private List<CookingMenu> items;
    private CookingMenuDao cookingMenuDao;
    private OperatorDao operatorDao;
    private MenuFoodMaterialDao foodMaterialDao;
    private ConfirmDialog confirmDialog;
    private int selectIndex = 0;
    private boolean enableDelete = true;
    private boolean enableUpdate = true;
    private CookingMenuMangerHelper cookingMenuMangerHelper;

    public EmnuControltemAdapter(Context context) {
        this.context = context;
        items = new ArrayList<>();
        confirmDialog = new ConfirmDialog(context, this);
        cookingMenuDao = new CookingMenuDao(context);
        foodMaterialDao = new MenuFoodMaterialDao(context);
        operatorDao = new OperatorDao(context);
        cookingMenuMangerHelper= CookingMenuMangerHelper.getInstance(context,new CookingMenuDao(context));
    }

    public void setActionEnable(boolean enableDelete,boolean enableUpdate) {
        this.enableDelete = enableDelete;
        this.enableUpdate = enableUpdate;
    }


    public List<CookingMenu> getData() {
        return items;
    }


    public void setItems(List<CookingMenu> data) {
        items.clear();
        if (data == null || data.isEmpty()) {
            notifyDataSetChanged();
            return;
        }
        items.addAll(data);
        notifyDataSetChanged();
    }

    public void clearData() {
        items.clear();
        notifyDataSetChanged();
    }


    @Override
    public int getCount() {
        return items == null ? 0 : items.size();
    }

    @Override
    public CookingMenu getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        try {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(context, R.layout.adapter_menu_control_item, null);
                holder.tv_name = convertView.findViewById(R.id.tv_name);
                holder.tv_up = convertView.findViewById(R.id.tv_up);
                holder.ivD = convertView.findViewById(R.id.ivD);
                holder.ivU = convertView.findViewById(R.id.ivU);
                holder.ivE = convertView.findViewById(R.id.ivE);
                holder.ivStd = convertView.findViewById(R.id.ivStd);
                holder.ivD.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
                holder.ivU.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
                holder.ivE.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
                holder.ivStd.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            String name = items.get(position).getName();
            holder.tv_name.setText(name+"("+items.get(position).getSpecification()+"斤)");
            int flag = items.get(position).getUploaded();
            holder.tv_up.setTextColor(0xFF000000);
            if (flag == 0) {
                holder.tv_up.setText("未上传");
                holder.tv_up.setTextColor(0xFFFF0000);
            } else {
                holder.tv_up.setText("已上传");
            }
            holder.ivD.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (enableDelete) {
                        delete(position);
                    }else {
                        showToast("无删除权限");
                    }
                }
            });
            holder.ivU.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (enableUpdate) {
                        upload(position);
                    }else {
                        showToast("无上传权限");
                    }
                }
            });
            holder.ivE.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    selectIndex = position;
                    updateInfo(items.get(position));
                }
            });
            holder.ivStd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    selectIndex = position;
                    updateStdMenuInfo(items.get(position));
                }
            });
        }catch (Exception e){
            Log.e(TAG,"getView Exception:"+e.getMessage());
        }
        return convertView;
    }

    private void updateStdMenuInfo(CookingMenu cookingMenu) {
//        showToast("设置标准菜谱");
        confirmDialog.showDialog("确定把" + cookingMenu.getName()+"设置成标准菜谱", 4);
    }

    private void updateInfo(CookingMenu cookingMenu) {
//        showToast("更新菜谱");
        confirmDialog.showDialog("确定更新" + cookingMenu.getName(), 3);
    }



    private void delete(int position) {
        selectIndex = position;
        CookingMenu cookingMenu = items.get(position);
        confirmDialog.showDialog("确定删除" + cookingMenu.getName(), 1);
    }

    private void upload(int position) {
        selectIndex = position;
        CookingMenu cookingMenu = items.get(position);
        confirmDialog.showDialog("确定上传" + cookingMenu.getName(), 2);
    }

    @Override
    public void selectResult(int value, int id) {
        if (value == -1) {
            selectIndex = -1;
            return;
        }
        if (id == 1) {
            //删除
            if (selectIndex != -1) {
                deleteItem(items.get(selectIndex));
                items.remove(selectIndex);
                notifyDataSetChanged();
            } else {
                toastMsg("未选中上传的菜谱");
            }
        }else if (id == 2) {
            //上传
            if (selectIndex != -1) {
                uploadEmnu(items.get(selectIndex));
            } else {
                toastMsg("未选中上传的菜谱");
            }
        }else if (id == 3) {
            //更新
            if (selectIndex != -1) {
                SendData.sendUpdateMenuInfo(items.get(selectIndex).getId(),items.get(selectIndex).getMachineModoel(),context,cookingMenuDao);
            } else {
                toastMsg("未选中更新的菜谱");
            }
        }else if (id == 4) {
            //更新
            if (selectIndex != -1) {
                setStdMenu(items.get(selectIndex));
            } else {
                toastMsg("未选中更新的菜谱");
            }
        }
    }

    private void setStdMenu(CookingMenu cookingMenu){
        if(Integer.parseInt(cookingMenu.getSpecification())>1){
            showToast("大于1斤的菜谱不能设置为标准菜谱");
            return;
        }
        if(!cookingMenuMangerHelper.isHasCat(cookingMenu.getName())){
            showToast("该菜谱没有分类标签，请添加分类标签");
            return;
        }
        if(cookingMenu.getName().contains("Z")){
            showToast("炒菜机端不能上传其他烹饪类型的菜谱");
            return;
        }
        cookingMenu.setOperators(operatorDao.queryForAllByMID(cookingMenu.getId()));
        cookingMenu.setFoodMaterials(foodMaterialDao.queryForAllByCId(cookingMenu.getId()));
        SendData.sendMenuInfo(context, cookingMenu,1);
    }

    private void deleteItem(CookingMenu cookingMenu) {
        try {
            cookingMenuDao.delete(cookingMenu);
            foodMaterialDao.deleteForCid(cookingMenu.getId());
            operatorDao.deleteByCid(cookingMenu.getId());
            showToast("删除成功");
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }

    }

    private void showToast(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    private void uploadEmnu(CookingMenu cookingMenu) {
        if(!cookingMenuMangerHelper.isHasCat(cookingMenu.getName())){
            showToast("该菜谱没有分类标签，请添加分类标签");
            return;
        }
        if(cookingMenu.getName().contains("Z")){
            showToast("炒菜机端不能上传其他烹饪类型的菜谱");
            return;
        }
        cookingMenu.setOperators(operatorDao.queryForAllByMID(cookingMenu.getId()));
        cookingMenu.setFoodMaterials(foodMaterialDao.queryForAllByCId(cookingMenu.getId()));
        SendData.sendMenuInfo(context, cookingMenu,0);
    }

    static class ViewHolder {
        TextView tv_name, tv_date, tv_up,ivD, ivU,ivE,ivStd;
//        ImageView ivD, ivU;
    }

    private void toastMsg(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT);
    }

}